package com.chen.utils;

import com.chen.vo.CustomException;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

//    秘钥
    private static final String jwtToken = "123456Mszlu!@#$$";

    public static String createToken(Long userId){
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId",userId);
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, jwtToken) // 签发算法，秘钥为jwtToken
                .setClaims(claims) // body数据，要唯一，自行设置
                .setIssuedAt(new Date())// 设置签发时间 24 * 60 * 60 * 60 * 1000
               .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 60 * 1000));// 三天的有效时间
        String token = jwtBuilder.compact();
        return token;
    }

//    解析token
    public static Map<String, Object> checkToken(String token){
        try {
            Jwt parse = Jwts.parser().setSigningKey(jwtToken).parse(token);
            return (Map<String, Object>) parse.getBody();
        }catch (ExpiredJwtException e){
            e.printStackTrace();
//            "登录过期，请重新登录！"
          throw new CustomException(10003,"登录过期，请重新登录！");
        }catch (UnsupportedJwtException e){
//            "Tonken不合法，请自重！"
            throw new CustomException(9999,"Tonken不合法，请自重！");
        }catch (Exception e) {
            throw new CustomException(9999,"出现未知异常请联系管理员~");
        }
    }

    //获取用户id
    public static Long getUserId(String token) {
        Object userIdObj = checkToken(token).get("userId");
        if (userIdObj instanceof Integer) {
            return ((Integer) userIdObj).longValue();
        } else if (userIdObj instanceof Long) {
            return (Long) userIdObj;
        } else {
            throw new IllegalArgumentException("Unexpected type for userId: " + userIdObj.getClass());
        }
    }



}
